package com.project.communitymanagement.service.impl;

import com.project.communitymanagement.common.BaseServiceImpl;
import com.project.communitymanagement.common.Page;
import com.project.communitymanagement.entity.TbHome;
import com.project.communitymanagement.entity.TbOwner;
import com.project.communitymanagement.mapper.TbOwnerMapper;
import com.project.communitymanagement.service.TbOwnerService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName: community-management
 * @Package: com.project.communitymanagement.service.impl
 * @ClassName: TbOwnerServiceImpl
 * @Author: "XGP"
 * @Description:
 * @Date: 2022/3/13 12:31
 * @Version: 1.0
 */
@Service
public class TbOwnerServiceImpl extends BaseServiceImpl<TbOwnerMapper, TbOwner> implements TbOwnerService {

    @Autowired
    private TbOwnerMapper tbownerMapper;

    @Override
    protected TbOwnerMapper mapper() {
        return tbownerMapper;
    }

    @Override
    protected TbOwner defaultModel() {
        return new TbOwner();
    }

    public Page<TbOwner> reportList(Page<TbOwner> page) {
        TbOwner userName = getUserName();
        if((page.getRequestData().getCreate_user() != null && page.getRequestData().getCreate_user().equals("admin"))||userName.getRole_id() == 0){
            page.getRequestData().setCreate_user(null);
        }
        if(page.getRequestData()==null)
            page.setRequestData(defaultModel());
        List<TbOwner> lst =mapper().getPageReport(page);
        int count = mapper().getTotalReport(page);
        return Page.getPage(lst,count);
    }

    @Override
    public String reportListDown(Page<TbOwner> page) {
        TbOwner data = page.getRequestData();
        TbOwner userName = getUserName();
        if((data.getCreate_user() != null && data.getCreate_user().equals("admin"))||userName.getRole_id() == 0){
            data.setCreate_user(null);
        }
        List<TbOwner> lst =mapper().reportListDown(page);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat formatData = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String fileName = data.getDownName()+ format.format(new Date()) + ".csv";
        try (CSVPrinter printer = new CSVPrinter(new FileWriter("C:\\images\\" + fileName ), CSVFormat.DEFAULT)) {
            List<String> header = Arrays.asList(
                    "序号", "真实姓名", "登录名", "薪资",
                    "年龄", "性别", "手机", "地址",
                    "职位", "生日", "创建人", "创建时间",
                    "入职时间"
            );
            printer.printRecord(header);

            for (int i = 0; i < lst.size(); i++) {
                TbOwner owner = lst.get(i);
                List<Object> list = new ArrayList<>();
                list.add(i);
                list.add(owner.getName());
                list.add(owner.getUsername());
                list.add(owner.getSalary());
                list.add(owner.getAge());
                list.add(owner.getSex());
                list.add(owner.getPhone());
                list.add(owner.getAddress());
                list.add(owner.getPosition());
                list.add(owner.getBirthday());
                list.add(owner.getCreate_user());
                list.add(formatData.format(owner.getCreate_date()));
                list.add(owner.getEntry_time() != null ? formatData.format(owner.getEntry_time()) : owner.getEntry_time());
                printer.printRecord(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @Override
    public Page<TbOwner> getPages(Page<TbOwner> page) {
        if (!("admin".equals(page.getRequestData().getCreate_user()))) {
            page.getRequestData().setUsername(page.getRequestData().getCreate_user());
        }
        return super.getPages(page);
    }

    @Override
    public int save(TbOwner tbOwner) {
        if (tbOwner.getId() == null) {
            TbOwner username = tbownerMapper.getUserByUsername(tbOwner.getUsername());
            if (username != null) {
                throw new RuntimeException("当前用户已存在，请勿重复添加！");
            }
        }
        return super.save(tbOwner);
    }

    @Override
    public List<TbOwner> getAll() {
        return tbownerMapper.getAll();
    }

    @Override
    public TbOwner getUserName() {
        String create_user = SecurityContextHolder.getContext().getAuthentication() != null
                ? SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User
                ? ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
                : null
                : null;
        return tbownerMapper.getUserByUsername(create_user);
    }

    @Override
    public Map<String,List<TbHome>> getDataByHome() {
        Map<String,List<TbHome>> map = new HashMap<>();
        List<TbHome> entryNum = tbownerMapper.getEntryNum();
        List<TbHome> distribution = tbownerMapper.getSalaryDistribution();
        List<TbHome> positionDistribution = tbownerMapper.getPositionDistribution();
        map.put("entryNum",entryNum);
        map.put("distribution",distribution);
        map.put("positionDistribution",positionDistribution);
        return map;
    }
}

